class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums) {
        vector<vector<int> > res;
        if(nums.size() < 3) return res;
        sort(nums.begin(),nums.end());
        int l = 0;
        int r = nums.size() - 1;
        int x = 1;
       for( l = 0;l < nums.size();l++){
           if(nums[l] > 0) return res;
           if(l > 0 && nums[l] == nums[l - 1]){
               continue;
           }
           x = l + 1;
           r = nums.size() - 1;
           while(x < r){
               if(nums[l] + nums[x] + nums[r] == 0){
                   res.push_back(vector<int>{nums[l],nums[x],nums[r]});
                   x++; r--;
                  while(x < r && nums[r] == nums[r + 1]) r--;
                  while(x < r && nums[x] == nums[x - 1]) x++;
               }
               if( nums[l] + nums[x] + nums[r] > 0){
                   r--;
                   while(x < r && nums[r] == nums[r + 1]){
                       r--;
                   }
               }
               if(nums[l] + nums[x] + nums[r] < 0){
                   x++;
                   while(x < r && nums[x] == nums[x - 1]){
                       x++;
                   }
               }
           }
       }
        return res;
        
    }
};
